# -*-coding:utf-8-*-
from books.models import Books
from celery_tasks.main import app
from django.template import loader
from django.conf import settings
import os

from books.utils import get_categories
from contents.models import ContentCategory


@app.task(name='generate_static_list_search_html')
def generate_static_list_search_html():
    """
    生成静态的图书列表页和搜索结果页html文件
    """
    # 图书分类菜单
    categories = get_categories()

    # 渲染模板，生成静态html文件
    context = {
        'categories': categories,
    }

    template = loader.get_template('search.html')
    html_text = template.render(context)
    file_path = os.path.join(settings.GENERATED_STATIC_HTML_FILES_DIR, 'search.html')
    with open(file_path, 'w', encoding='utf-8') as f:
        f.write(html_text)

    template = loader.get_template('list.html')
    html_text = template.render(context)
    file_path = os.path.join(settings.GENERATED_STATIC_HTML_FILES_DIR, 'list.html')
    with open(file_path, 'w') as f:
        f.write(html_text)

@app.task(name='generate_static_index_html')
def generate_static_index_html():
    """
    生成静态的主页html文件
    """

    # 图书分类菜单
    categories = get_categories()

    # 广告内容
    contents = {}
    content_categories = ContentCategory.objects.all()
    for cat in content_categories:
        contents[cat.key] = cat.content_set.filter(status=True).order_by('sequence')

    # 渲染模板
    context = {
        'categories': categories,
        'contents': contents
    }

    template = loader.get_template('index.html')
    html_text = template.render(context)
    file_path = os.path.join(settings.GENERATED_STATIC_HTML_FILES_DIR, 'index.html')
    with open(file_path, 'w', encoding='utf-8') as f:
        f.write(html_text)


@app.task(name='generate_static_book_detail_html')
def generate_static_book_detail_html(book_id):
    """
    生成静态商品详情页面
    :param book_id: 图书book_id
    :return:
    """
    # 商品分类信息
    categories = get_categories()

    # 获取当前book的信息
    book = Books.objects.get(id=book_id)
    book.image = book.image_url.url

    # 面包屑导航
    book.channel = book.category3.parent.parent.bookschannel_set.all()[0]

    # 渲染模板，生成静态html文件
    context = {
        'categories': categories,
        # 'goods': goods,
        # 'specs': specs,
        'book': book,
    }

    template = loader.get_template('detail.html')
    html_text = template.render(context)
    file_path = os.path.join(settings.GENERATED_STATIC_HTML_FILES_DIR, 'books/' + str(book_id) + '.html')
    with open(file_path, 'w') as f:
        f.write(html_text)


